import Footer from '@/components/Footer';
import { doFetch, postFetch } from '@/utils/doFetch';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, useModel } from '@umijs/max';
import { Tabs } from 'antd';
import { useState } from 'react';

const Login = () => {
  const {
    initialState: { currentUser, fetchUserInfo },
    setInitialState,
  } = useModel('@@initialState');
  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });

  const handleSubmit = async (values) => {
    if (loginType === 'account') {
      // 登录
      const msg = await doFetch({
        url: '/webtool/login',
        params: {
          user_name: values?.username,
          password: values?.password,
        },
      });
      if (msg.code === 0) {
        localStorage.setItem('TOKENES', msg?.data);
        const currentUser = await fetchUserInfo();
        localStorage.setItem("ID",currentUser?.id)
        await setInitialState((s) => {
          return {
            ...s,
            fetchUserInfo,
            currentUser,
          };
        });
        localStorage.setItem('REG', '2333');
        history.push('/welcome');
      }
    } else {
      // 登录
      const msg = await postFetch({
        url: '/webtool/v1/user',
        params: {
          user_name: values?.username,
          password: values?.password,
        },
      });
      if (msg.code === 0) {
        localStorage.setItem('REG', '2333');
        setLoginType('account');
      }
    }
  };

  const [loginType, setLoginType] = useState(!localStorage.getItem('REG') ? 'phone' : 'account');

  return (
    <div className={containerClassName}>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="./logo.png" style={{ borderRadius: '50%' }} />}
          title={<span className="bgtext">Tasks Tracking</span>}
          subTitle={'———用于小团队简单的任务开发实时跟踪'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
          submitter={{
            searchConfig: {
              submitText: loginType === 'account' ? '登录' : '注册',
            },
          }}
        >
          <Tabs activeKey={loginType} onChange={(activeKey) => setLoginType(activeKey)}>
            <Tabs.TabPane key={'account'} tab={'登录'} />
            <Tabs.TabPane key={'phone'} tab={'注册'} />
          </Tabs>
          {loginType === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'用户名'}
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <div
                style={{
                  marginBottom: 24,
                }}
              >
                <ProFormCheckbox noStyle name="autoLogin">
                  自动登录
                </ProFormCheckbox>
                <a
                  style={{
                    float: 'right',
                  }}
                >
                  忘记密码
                </a>
              </div>
            </>
          )}
          {loginType === 'phone' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'用户名'}
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <ProFormText.Password
                name="confirm"
                dependencies={['password']}
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'确认密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次密码不一致!'));
                    },
                  }),
                ]}
              />
            </>
          )}
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
